package com.sec.base.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

public class FileUtil {

	/**
	 * @param file     文件
	 * @param path     文件存放路径
	 * @param fileName 保存的文件名
	 * @return
	 */
	public static File upload(MultipartFile file, String path, String fileName) {
		// 确定上传的文件名
		String realPath = path + "\\" + fileName;
		System.out.println("上传文件：" + realPath);
		File dest = new File(realPath);
		// 判断文件父目录是否存在
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdir();
		}
		try {
			// 保存文件
			file.transferTo(dest);
			return dest;
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String encodeBase64File(String path) {
		String base64 = null;
		InputStream in = null;
		try {
			File file = new File(path);
			in = new FileInputStream(file);
			byte[] bytes = new byte[in.available()];
			base64 = Base64Utils.encodeToString(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return base64;
	}
}
